<template>
  <div class="container">
    <div class="box box-ver w-p100 h-p100">
      <div class="search box box-ac">
        <div class="icon icon-search"></div>
        <input placeholder="搜索" v-model="searchWord" class="box-f1" type="text">
      </div>
      <div class="box box-ver box-f1 of-y-s">
        <div v-if="locList.length > 0" class="tag">
          常用选择
        </div>
        <div v-if="locList.length > 0" class="list list1">
          <div v-for="(item, index) in locList" :value="item" :key="index" class="item box box-ver">
            <div class="name ell tc-333">{{item.depName}}</div>
            <div class="code tc-999">编号：{{item.depNumber}}</div>
          </div>
        </div>
        <div v-if="searchList.length > 0" class="tag">
          所有公司
        </div>
        <div  v-if="searchList.length > 0" class="list list1">
          <div @click="checkItem(item)" v-for="(item, index) in searchList" :value="item" :key="index" class="item box box-ver">
            <div class="name ell">{{item.depName}}</div>
            <div class="code tc-999">编号：{{item.depNumber}}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'selectDep',
  data () {
    return {
      dataList: [],
      searchList: [],
      locList: [],
      searchWord: '',
      timer: null
    }
  },
  computed: mapState(['userNum']),
  mounted () {
    this.getCsDep()
  },
  watch: {
    searchWord () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.search()
      }, 666)
    }
  },
  methods: {
    checkItem (item) {
      let { from, index } = this.$route.query
      let { depName, depNumber } = item
      if (from === 'xinCenStep3') {
        this.$emit('selectCompanyCallBack', {
          index,
          depNumber,
          depName
        })
      } else {
        this.$store.commit('bizAccountBill', {
          costCenterName: depName,
          costDeptNum: depNumber
        })
      }
      this.$router.go(-1)
    },
    search () {
      let searchWord = this.searchWord
      let list = []
      this.dataList.forEach(item => {
        if (item.depName.indexOf(searchWord) > -1 || item.depNumber.indexOf(searchWord) > -1) {
          list.push(item)
        }
      })
      this.searchList = list
    },
    getCsDep () {
      this.$http({
        url: this.$config.api.host,
        data: {
          method: 'getCsDep',
          userNum: this.userNum,
          companyNum: this.$route.query.companyNum
        }
      }).then(res => {
        if (res.code === 200) {
          this.dataList = res.t.sort((a, b) => {
            return (a.depNumber).localeCompare(b.depNumber)
          })
          this.searchList = this.dataList
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../assets/css/search';
.container{
  z-index:3;
}
</style>
